<template>
  <view class="schedule-query-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="排班查询" :autoBack="true" :fixed="true" bgColor="transparent" :border="false" placeholder>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 查询类型切换 -->
            <view class="filter-item">
              <text class="filter-label">查询方式：</text>
              <up-tabs :list="queryTypeList" :scrollable="false" @change="handleQueryTypeChange" :current="currentQueryType"></up-tabs>
            </view>
            
            <!-- 班次筛选 -->
            <view class="filter-item" v-if="currentQueryType === 0">
              <text class="filter-label">班次筛选：</text>
              <picker :value="shiftIndex" :range="shiftOptions" range-key="text" @change="handleShiftPickerChange">
                <view class="picker-view">
                  <text>{{ currentShiftText }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
            </view>
            
            <!-- 工作站筛选 -->
            <view class="filter-item" v-if="currentQueryType === 1">
              <text class="filter-label">工作站筛选：</text>
              <picker :value="workstationIndex" :range="workstationOptions" range-key="text" @change="handleWorkstationPickerChange">
                <view class="picker-view">
                  <text>{{ currentWorkstationText }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
            </view>
            
            <!-- 人员姓名搜索 -->
            <view class="filter-item" v-if="currentQueryType === 2">
              <text class="filter-label">人员姓名：</text>
              <up-search 
                v-model="searchForm.nameKeyword" 
                :clearabled="true" 
                :showAction="true" 
                placeholder="请输入人员姓名" 
                @custom="handleSearch" 
                @clear="handleClear"
              >
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                  <up-button type="default" size="small" @click="handleClear" style="margin-left: 5px;">重置</up-button>
                </template>
              </up-search>
            </view>
            
            <!-- 日期选择 -->
            <view class="filter-item">
              <text class="filter-label">日期选择：</text>
              <view class="date-picker">
                <picker mode="date" :value="searchForm.date" @change="handleDatePickerChange">
                  <view class="picker-view">
                    <text>{{ searchForm.date }}</text>
                    <text class="picker-arrow">▼</text>
                  </view>
                </picker>
              </view>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 排班列表 -->
      <view class="schedule-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              <text class="name">{{ item.name }}</text>
              <up-tag :text="item.roleName" type="primary" size="small" class="role-tag"></up-tag>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>
          <view class="card-content">
            <view class="info-row">
              <view class="info-item">
                <text class="label">工号：</text>
                <text class="value">{{ item.employeeId }}</text>
              </view>
              <view class="info-item">
                <text class="label">手机号：</text>
                <text class="value">{{ item.phone }}</text>
              </view>
            </view>
            <view class="info-row">
              <view class="info-item">
                <text class="label">工作站：</text>
                <text class="value">{{ item.workArea }}</text>
              </view>
              <view class="info-item">
                <text class="label">班次：</text>
                <text class="value">{{ item.currentShift || '未排班' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';

// z-paging 组件引用
const paging = ref(null);

// picker索引
const shiftIndex = ref(0);
const workstationIndex = ref(0);

// 查询类型选项
const queryTypeList = [
  { name: '按班次查询' },
  { name: '按工作站查询' },
  { name: '按人员姓名查询' }
];
const currentQueryType = ref(0);

// 班次选项
const shiftOptions = ref([
  { text: '全部班次', value: '' },
  { text: '早班 (08:00-16:00)', value: '早班 (08:00-16:00)' },
  { text: '中班 (16:00-24:00)', value: '中班 (16:00-24:00)' },
  { text: '夜班 (00:00-08:00)', value: '夜班 (00:00-08:00)' }
]);
const currentShift = ref('');
const currentShiftText = computed(() => {
  const selected = shiftOptions.value.find(item => item.value === currentShift.value);
  return selected ? selected.text : '全部班次';
});

// 工作站选项
const workstationOptions = ref([
  { text: '全部工作站', value: '' },
  { text: '区域1', value: '区域1' },
  { text: '区域2', value: '区域2' },
  { text: '区域3', value: '区域3' },
  { text: '区域4', value: '区域4' },
  { text: '区域5', value: '区域5' }
]);
const currentWorkstation = ref('');
const currentWorkstationText = computed(() => {
  const selected = workstationOptions.value.find(item => item.value === currentWorkstation.value);
  return selected ? selected.text : '全部工作站';
});

// 加载班次和工作站选项
const loadOptions = async () => {
  try {
    // 实际项目中应该调用API获取选项数据
    // const shiftResponse = await getShiftList({});
    // if (shiftResponse && shiftResponse.data) {
    //   const shifts = shiftResponse.data.map(item => ({
    //     text: item.name,
    //     value: item.value
    //   }));
    //   shiftOptions.value = [{ text: '全部班次', value: '' }, ...shifts];
    // }
    // 
    // const workstationResponse = await getWorkstationList({});
    // if (workstationResponse && workstationResponse.data) {
    //   const workstations = workstationResponse.data.map(item => ({
    //     text: item.name,
    //     value: item.value
    //   }));
    //   workstationOptions.value = [{ text: '全部工作站', value: '' }, ...workstations];
    // }
  } catch (error) {
    console.error('加载选项数据失败:', error);
  }
};

// 搜索表单
const searchForm = reactive({
  nameKeyword: '',
  date: formatDate(new Date())
});

// 当前列表数据
const currentList = ref([]);

// 查询类型切换事件
const handleQueryTypeChange = (e) => {
  currentQueryType.value = e.index;
  if (paging.value) {
    paging.value.reload();
  }
};

// 班次选择事件 - picker版本
const handleShiftPickerChange = (e) => {
  const index = e.detail.value;
  shiftIndex.value = index;
  currentShift.value = shiftOptions.value[index].value;
  if (paging.value) {
    paging.value.reload();
  }
};

// 工作站选择事件 - picker版本
const handleWorkstationPickerChange = (e) => {
  const index = e.detail.value;
  workstationIndex.value = index;
  currentWorkstation.value = workstationOptions.value[index].value;
  if (paging.value) {
    paging.value.reload();
  }
};

// 日期选择事件 - picker版本
const handleDatePickerChange = (e) => {
  const dateValue = e.detail.value;
  searchForm.date = dateValue;
  if (paging.value) {
    paging.value.reload();
  }
};

// 原日期选择事件（保留以兼容）
const handleDateChange = (e) => {
  searchForm.date = e;
  if (paging.value) {
    paging.value.reload();
  }
};

// 搜索事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清除搜索事件
const handleClear = () => {
  searchForm.nameKeyword = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'active':
      return 'status-active';
    case 'disabled':
      return 'status-disabled';
    default:
      return '';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'active':
      return '在岗';
    case 'disabled':
      return '离岗';
    default:
      return '未知';
  }
};

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 构建查询参数
    const params = {
      pageNum: pageNo,
      pageSize,
      date: searchForm.date
    };

    // 根据查询类型添加不同的参数
    if (currentQueryType.value === 0) {
      // 按班次查询
      params.shift = currentShift.value;
    } else if (currentQueryType.value === 1) {
      // 按工作站查询
      params.workArea = currentWorkstation.value;
    } else if (currentQueryType.value === 2) {
      // 按人员姓名查询
      params.nameKeyword = searchForm.nameKeyword;
    }

    // 模拟API调用，实际项目中应该调用真实的API
    const mockData = generateMockData(params);
    
    // 更新列表数据
    paging.value.complete(mockData.records || []);
  } catch (error) {
    console.error('查询排班数据失败:', error);
    paging.value.complete(false);
  }
};

// 生成模拟数据
const generateMockData = (params) => {
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十', '郑十一', '王十二'];
  const roles = [
    { id: 'inspector', name: '巡检员' },
    { id: 'leader', name: '组长' },
    { id: 'supervisor', name: '主管' }
  ];
  const shifts = ['早班 (08:00-16:00)', '中班 (16:00-24:00)', '夜班 (00:00-08:00)'];
  const workAreas = ['区域1', '区域2', '区域3', '区域4', '区域5'];
  
  let records = [];
  
  // 生成10条模拟数据
  for (let i = 0; i < 10; i++) {
    const role = roles[Math.floor(Math.random() * roles.length)];
    const isActive = Math.random() > 0.2;
    const shift = shifts[Math.floor(Math.random() * shifts.length)];
    const workArea = workAreas[Math.floor(Math.random() * workAreas.length)];
    
    const record = {
      id: i + 1,
      name: names[i % names.length],
      phone: `138${Math.random().toString().substr(2, 8)}`,
      employeeId: `EMP${(i + 1).toString().padStart(4, '0')}`,
      roleId: role.id,
      roleName: role.name,
      status: isActive ? 'active' : 'disabled',
      workArea: workArea,
      currentShift: shift
    };
    
    // 根据查询参数过滤数据
    let shouldInclude = true;
    
    // 按班次筛选
    if (params.shift && record.currentShift !== params.shift) {
      shouldInclude = false;
    }
    
    // 按工作站筛选
    if (params.workArea && record.workArea !== params.workArea) {
      shouldInclude = false;
    }
    
    // 按人员姓名筛选
    if (params.nameKeyword && !record.name.includes(params.nameKeyword)) {
      shouldInclude = false;
    }
    
    if (shouldInclude) {
      records.push(record);
    }
  }
  
  // 确保至少有一些数据显示
  if (records.length === 0) {
    // 添加一条默认数据
    records.push({
      id: 1,
      name: '张三',
      phone: '13800138000',
      employeeId: 'EMP0001',
      roleId: 'inspector',
      roleName: '巡检员',
      status: 'active',
      workArea: '区域1',
      currentShift: '早班 (08:00-16:00)'
    });
  }
  
  return { records };
};

// 页面加载时初始化数据
onMounted(async () => {
  // 加载班次和工作站选项
  await loadOptions();
  
  // 加载排班数据
  if (paging.value) {
    paging.value.reload();
  }
});
</script>

<style lang="scss" scoped>
.schedule-query-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.filter-section {
  background-color: #ffffff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.picker-view {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10rpx 20rpx;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  font-size: 28rpx;
  height: 60rpx;
  width: 300rpx;
}

.picker-arrow {
  font-size: 24rpx;
  color: #909399;
  margin-left: 10rpx;
}

.filter-item {
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.filter-label {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 10rpx;
  display: block;
}

.date-picker {
  background-color: #f8f8f8;
  border-radius: 8rpx;
  padding: 10rpx;
}

.schedule-list {
  padding: 0 20rpx;
}

.list-item-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  
  .title {
    display: flex;
    align-items: center;
    
    .name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      margin-right: 10rpx;
    }
    
    .role-tag {
      margin-left: 10rpx;
    }
  }
  
  .status-badge {
    font-size: 24rpx;
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
    
    &.status-active {
      background-color: #e6f7ff;
      color: #1890ff;
    }
    
    &.status-disabled {
      background-color: #fff1f0;
      color: #ff4d4f;
    }
  }
}

.card-content {
  .info-row {
    display: flex;
    margin-bottom: 12rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .info-item {
      flex: 1;
      display: flex;
      align-items: center;
      
      .label {
        font-size: 26rpx;
        color: #666666;
        margin-right: 8rpx;
      }
      
      .value {
        font-size: 26rpx;
        color: #333333;
      }
    }
  }
}
</style>